#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <ctime>
#include "RingQueue.hpp"

using namespace std;

struct ThreadData
{
    RingQueue<int> *rq;
    string threadname;
};

void *Productor(void *args)
{
    ThreadData* td  = static_cast<ThreadData*>(args);
    RingQueue<int> *rq = td->rq;
    string name = td->threadname;

    // sleep(3);
    while (true)
    {
        // 1.先获取数据
        int data = rand() % 10 + 1;

        // 2.生产数据
        rq->Push(data);
        cout << "Productor data done, data is :" << data << "who: "<< name << endl;
        // sleep(2);
    }

    return nullptr;
}

void *Consumer(void *args)
{
    ThreadData* td  = static_cast<ThreadData*>(args);
    RingQueue<int> *rq = td->rq;
    string name = td->threadname;

    while (true)
    {
        // 1.消费数据
        int data = 0;
        rq->Pop(&data);

        // 2.处理数据
        cout << "Consumer get data, data is :" << data << "who: "<< name << endl;
        sleep(1);
    }
    return nullptr;
}

int main()
{
    srand(time(nullptr) ^ getpid()); // 随机数种子 再异或

    RingQueue<int> *rq = new RingQueue<int>();
    pthread_t c[5], p[3];

    for (int i = 0; i < 3; ++i)
    {
        ThreadData *td = new ThreadData();
        td->rq = rq;
        td->threadname = "Productor-" + to_string(i);

        pthread_create(p + i, nullptr, Productor, td);
    }

    for (int i = 0; i < 5; ++i)
    {
        ThreadData *td = new ThreadData();
        td->rq = rq;
        td->threadname = "Consumer-" + to_string(i);

        pthread_create(c + i, nullptr, Consumer, td);
    }

    for (int i = 0; i < 3; ++i)
    {
        pthread_join(p[i], nullptr);
    }

    for (int i = 0; i < 5; ++i)
    {
        pthread_join(c[i], nullptr);
    }

    // 这样两个线程能看到同一个对象
    //  pthread_create(&p, nullptr, Productor, rq);
    //  pthread_create(&c, nullptr, Consumer, rq);

    // pthread_join(c, nullptr);
    // pthread_join(p, nullptr);
}